<template>
  <div class="video-container w-full h-full">
    <video
      ref="videoRef"
      class="video-js vjs-default-skin vjs-big-play-centered vjs-live"
      :id="playerId"
      muted
    ></video>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import videojs from 'video.js'
import 'video.js/dist/video-js.css'
import Hls from 'hls.js'

const props = defineProps({
  src: {
    type: String,
    required: true,
  },
  playerId: {
    type: String,
    default: `player-${Date.now()}-${Math.random().toString(36).substring(2, 10)}`,
  },
  options: {
    type: Object,
    default: () => ({}),
  },
})

const videoRef = ref(null)
let player = null

// 初始化播放器
const initializePlayer = (videoElement) => {
  // 默认配置
  const defaultOptions = {
    controls: true,
    autoplay: true,
    preload: 'auto',
    // fluid: true,
    responsive: true,
    liveui: true, // 启用直播UI
    liveTracker: {
      trackingThreshold: 0,
      liveTolerance: 15,
    },
    controlBar: {
      // 为直播设置适当的控制栏
      children: [
        'playToggle',
        'volumePanel',
        'liveDisplay', // 添加直播指示器
        'spacer', // 添加空间将全屏按钮推到右侧
        'fullscreenToggle',
      ],
    },
    language: 'zh-CN',
  }

  // 合并自定义配置
  const finalOptions = {
    ...defaultOptions,
    ...props.options,
  }

  // 创建播放器实例
  return videojs(videoElement, finalOptions)
}

// 设置视频源
const setupVideoSource = (url) => {
  if (!player) return

  // 检查浏览器是否支持 HLS
  if (Hls.isSupported()) {
    const hls = new Hls({
      enableWorker: true,
      lowLatencyMode: true, // 启用低延迟模式
      liveDurationInfinity: true, // 将直播视频时长设为无限
    })

    hls.loadSource(url)
    hls.attachMedia(videoRef.value)

    hls.on(Hls.Events.MANIFEST_PARSED, () => {
      player.play()
    })

    // 错误处理
    hls.on(Hls.Events.ERROR, (event, data) => {
      console.error('HLS 错误:', data)
      if (data.fatal) {
        switch (data.type) {
          case Hls.ErrorTypes.NETWORK_ERROR:
            console.log('网络错误，尝试恢复...')
            hls.startLoad()
            break
          case Hls.ErrorTypes.MEDIA_ERROR:
            console.log('媒体错误，尝试恢复...')
            hls.recoverMediaError()
            break
          default:
            console.error('无法恢复的错误')
            hls.destroy()
            break
        }
      }
    })

    // 清理函数
    player.on('dispose', () => {
      hls.destroy()
    })
  }
  // 对于原生支持 HLS 的浏览器（如 Safari）
  else if (videoRef.value.canPlayType('application/vnd.apple.mpegurl')) {
    player.src({
      src: url,
      type: 'application/x-mpegURL',
      withCredentials: false,
    })
  }
}

// 监听源地址变化
watch(
  () => props.src,
  (newUrl) => {
    if (newUrl && player) {
      setupVideoSource(newUrl)
    }
  },
)

// 处理播放器控制栏布局
const setupControlBar = () => {
  // 确保使用特定ID选择器，只影响当前播放器实例
  const controlBar = document.querySelector(`#${props.playerId} .vjs-control-bar`)
  const spacer = document.querySelector(`#${props.playerId} .vjs-spacer`)
  const fullscreenButton = document.querySelector(`#${props.playerId} .vjs-fullscreen-control`)

  if (controlBar) {
    controlBar.style.display = 'flex'
    controlBar.style.flexDirection = 'row'
    controlBar.style.alignItems = 'center'
    controlBar.style.justifyContent = 'space-between'
  }

  if (spacer) {
    spacer.style.flexGrow = '1'
  }

  if (fullscreenButton) {
    fullscreenButton.style.order = '5'
  }

  // 隐藏进度条
  const progressControl = document.querySelector(`#${props.playerId} .vjs-progress-control`)
  if (progressControl) {
    progressControl.style.display = 'none'
  }
}

// 组件挂载时初始化
onMounted(() => {
  if (videoRef.value) {
    player = initializePlayer(videoRef.value)
    if (props.src) {
      setupVideoSource(props.src)
    }

    // 添加错误处理
    player.on('error', (error) => {
      console.error('播放器错误:', error)
    })

    // 设置为直播模式
    player.addClass('vjs-live')

    // 等待播放器完全初始化后再设置控制栏样式
    player.ready(() => {
      setupControlBar()

      // 播放器尺寸变化时重新应用样式
      player.on('resize', () => {
        setTimeout(setupControlBar, 100)
      })
    })

    // 额外的延迟设置，确保样式应用
    setTimeout(setupControlBar, 300)
  }
})

// 组件卸载时清理
onUnmounted(() => {
  if (player) {
    try {
      player.dispose()
      player = null
      console.log('清理成功')
    } catch (error) {
      console.error('清理播放器错误:', error)
    }
  }
})
</script>

<style scoped>
.video-container {
  position: relative;
  width: 100%;
  height: 100%;
}

:deep(.video-js) {
  width: 100% !important;
  height: 100% !important;
  background-color: transparent;
}

:deep(.vjs-default-skin) {
  background-color: transparent;
}

/* CSS样式仍然保留，作为备用 */
:deep(.vjs-control-bar) {
  background-color: rgba(0, 0, 0, 0.7) !important;
  display: flex !important;
  flex-direction: row !important;
  align-items: center !important;
  justify-content: space-between !important;
}

:deep(.vjs-spacer) {
  flex-grow: 1 !important;
}

:deep(.vjs-live-display) {
  margin-left: 10px;
  background-color: rgba(255, 0, 0, 0.6);
  border-radius: 3px;
  padding: 2px 5px;
}

:deep(.vjs-progress-control) {
  display: none !important;
}

:deep(.vjs-live) .vjs-time-display,
:deep(.vjs-live) .vjs-duration,
:deep(.vjs-live) .vjs-progress-control {
  display: none !important;
}
</style>
